package com.mmp.main.servlet.joborder;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import com.mmp.common.bo.Message;
import com.mmp.common.servlet.BasicServlet;
import com.mmp.main.endpoints.JobOrderNotificationsEndPoint;
import com.mmp.main.entity.HospitalDevice;
import com.mmp.main.entity.JobOrder;
import com.mmp.main.util.Default;
import com.mmp.main.util.Enums;
import com.mmp.main.util.WebUtil;

public class JobOrderDeleteProcessServlet extends BasicServlet {

	@Autowired
	JobOrderNotificationsEndPoint joNotifier;

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		int jobOrderId = WebUtil.getParamValueAsInteger(request, "jobOrderId", 0);
		int deviceId = WebUtil.getParamValueAsInteger(request, "deviceId", 0);

		if (deviceId == 0 || jobOrderId == 0) {
			announceErorrMessage(request, response, Default.GENERAL_ERROR_MESSAGE);
			return;
		}

		JobOrder order = dbQueryManager.findById(jobOrderId, JobOrder.class);

		HospitalDevice device = order.getHospitalDevice();
		device.setStatus(Enums.DEVICE_STATUS.WORK_PROPERLY.getStatus());

		order.setActualCancelDate(WebUtil.getParamValueAsDate(request, "actualCancelDate", null));
		order.setCancelReason(WebUtil.getParamValue(request, "cancelReason", null));
		order.setCancelled(true);
		order.setCancelledBy(getSessionUser(request));
		order.setCancelledIn(new Date());

		dbQueryManager.mergeEntity(order);

		setMessage(request, new Message("تم حذف أمر العمل بنجاح", Message.MESSAGE_TYPE.SUCCESS));

		joNotifier.broadcastNotificationUpdates(getSessionSiteId(request));

		sendRedirect(request, response, "CancelJobOrderSearch");
	}
}
